package com.topisv.tms.web.focus;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.BackupTask;
import com.topisv.tms.entity.BackupTaskOrdeno;
import com.topisv.tms.entity.BackupTaskSku;
import com.topisv.tms.entity.BatchTask;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.OrdenoSource;
import com.topisv.tms.entity.ShippedBoxSkus;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.dto.BackupTaskSkuDTO;
import com.topisv.tms.entity.dto.ShippedBoxDTO;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.BackupTaskOrdenoService;
import com.topisv.tms.service.BackupTaskService;
import com.topisv.tms.service.BackupTaskSkuService;
import com.topisv.tms.service.BatchTaskService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.OrdenoSourceService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.shipped.ShippedBoxService;
import com.topisv.tms.service.shipped.ShippedBoxSkusService;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.utils.store.GetSkuStoreUtil;
import com.topisv.tms.web.dto.GroupBackupTaskDTO;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * WMS生成分拣任务
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping(value = "/focusBackupTask")
public class FocusBackupTaskController {
	private static final Logger log = LoggerFactory.getLogger(FocusBackupTaskController.class);
	

	private static int PAGENUMBER = 100;

	@Autowired
	private BackupTaskService backupTaskService;
	@Autowired
	private BackupTaskSkuService backupTaskSkuService;
	@Autowired
	private ShippedBoxService shippedBoxService;
	@Autowired
	private BatchTaskService batchTaskService;
	@Autowired
	private BackupTaskOrdenoService backupTaskOrdenoService;
	@Autowired
	private ShippedBoxSkusService shippedBoxSkusService;
	@Autowired
	private ShopSourceService shopSourceService;
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private OrdenoSourceService ordenoSourceService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;

	/**
	 * 一键拣货
	 * 
	 * @param backupTaskCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxPickingCode")
	public void ajaxPickingCode(
			@RequestParam(value = "backupTaskCode") String backupTaskCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		BackupTask backupTask = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			backupTask = backupTaskService.findByBackupTaskCode(backupTaskCode);
			if (backupTask == null) {
				json.put("status", "1");
				json.put("content", "该拣货任务不存在");
				out.print(json.toString());
				return;
			}
			if ("finish".equals(backupTask.getPickStatus())) {
				json.put("status", "1");
				json.put("content", "该拣货任务已经完成拣货");
				out.print(json.toString());
				return;
			}
			if ("working".equals(backupTask.getPickStatus())) {
				json.put("status", "1");
				json.put("content", "生成拣货任务中");
				out.print(json.toString());
				return;
			}
			backupTask.setPickStatus("working");
			backupTaskService.save(backupTask);
			String content = backupTaskService
					.pickBackupTaskSku(backupTaskCode);
			json.put("status", "1");
			json.put("content", content);

			out.print(json.toString());
		} catch (Exception e) {
			backupTask.setPickStatus("pending");
			backupTaskService.save(backupTask);
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 商品拣货
	 * 
	 * @param backupTaskCode
	 * @param sku
	 * @param number
	 * @param response
	 */
	@RequestMapping(value = "ajaxPickingSku")
	public void ajaxPickingSku(
			@RequestParam(value = "backupTaskCode") String backupTaskCode,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "number") int number,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			BackupTaskSkuDTO backupTaskSkuDTO = backupTaskService
					.pickBackupTaskSku(backupTaskCode, sku, number);
			if (backupTaskSkuDTO == null) {
				json.put("status", "-1");
				json.put("content", "拣货失败:该商品不属于该拣货任务");
				out.print(json.toString());
				return;
			}

			if ("-1".equals(backupTaskSkuDTO.getStatus())) {
				json.put("status", "-1");
				json.put("content", backupTaskSkuDTO.getReserve());
			} else {
				json.put("status", "1");
				json.put("content", backupTaskSkuDTO.getReserve());
			}
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	@RequestMapping(value = "showOrdenos/{backupTaskCode}")
	public String showOrdenos(
			@PathVariable(value = "backupTaskCode") String backupTaskCode,
			Model model) {
		List<BackupTaskOrdeno> backupTaskOrdenos = null;
		List<EdiOrder> ediOrders = null;
		try {
			ediOrders = new ArrayList<EdiOrder>();
			backupTaskOrdenos = backupTaskOrdenoService
					.findByBackupTaskCode(backupTaskCode);
			for (BackupTaskOrdeno b : backupTaskOrdenos) {
				ediOrders.add(ediOrderService.findByOrdeno(b.getOrdeno()));
			}
			model.addAttribute("object", ediOrders);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}

		return "work/gather/showOrdenos";
	}

	/**
	 * 显示拣货列表
	 * 
	 * @param backupTaskCode
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "pickingSku/{backupTaskCode}")
	public String pickingSku(
			@PathVariable(value = "backupTaskCode") String backupTaskCode,
			Model model) {
		ShiroUser user = getShiroUser();
		BackupTask backupTask = null;
		List<BackupTaskSku> backupTaskSkus = null;
		try {
			backupTask = backupTaskService.setJobuuid(backupTaskCode,
					user.jobuuid, "picking");
			if (backupTask == null) {
				return "redirect:/focusBackupTask/backupTaskLists";
			} else {
				model.addAttribute("obj", backupTask);
				backupTaskSkus = backupTaskSkuService
						.findByBackupTaskCode(backupTaskCode);
				model.addAttribute("backupTaskSkus", backupTaskSkus);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}

		return "work/gather/pickingSku";
	}

	/**
	 * 显示未处理的拣货任务
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "backupTaskLists")
	public String backupTask(Model model) {
		// 查找商户组
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject()
				.getPrincipal();
		List<Customers> customerList = this.customersService
				.loadCustomerByAuthority(curUser);
		model.addAttribute("customers", customerList);

		String customerCode = customerList.get(0).getCustomerCode();
		Customers customer = this.customersService
				.findByCustomerCode(customerCode);
		model.addAttribute("customer", customer);

		// 集发目的地网点
		List<AreaGroup> areaGroups = this.areaGroupService
				.loadAreaGroupByAuthority(customerCode);// loadByWarehouseType("paiu");
		model.addAttribute("areaGroups", areaGroups);

		// 封装查询参数

		// 查询作业批次
		Map<String, Object> maps = new HashMap<String, Object>();
		maps.put("warehouseCode", curUser.areagroups);
		maps.put("status", "pending");
		if (StatusEnums.user_type_customer.getStatus().equals(curUser.userType)) {// 商家用户
			maps.put("customers", curUser.customerCode);
		} else if (StatusEnums.user_type_paiu.getStatus().equals(
				curUser.userType)) {// 派友用户
			maps.put("customers", curUser.customers);

		}
		List<BackupTask> workBatchList = this.backupTaskService
				.findBackupTaskStatus(maps);
		model.addAttribute("backupTasks", workBatchList);

		List<AreaGroup> wmList = this.areaGroupService
				.loadAreaGroupByAuthority(curUser, customerCode);
		model.addAttribute("wmList", wmList);
		model.addAttribute("status", 1);
		return "work/gather/backupTaskLists";
	}

	/**
	 * 根据拣货任务号获得商品信息
	 * 
	 * @param backupTaskCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxPrintBackupTaskSkus")
	public void ajaxPrintBackupTaskSkus(
			@RequestParam(value = "backupTaskCode") String backupTaskCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			List<BackupTaskSku> backupTaskSkus = backupTaskSkuService
					.findByBackupTaskCode(backupTaskCode);
			if (backupTaskSkus.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "请检查备货任务号是否正确");
				out.print(json.toString());
				return;
			}
			BackupTask backupTask = backupTaskService
					.findByBackupTaskCode(backupTaskCode);
			BatchTask batchTask = batchTaskService
					.findByBatchTaskCode(backupTask.getBatchTaskCode());
			OrdenoSource ordenoSource = ordenoSourceService
					.findByOrdenoSourceCode(batchTask.getShopSourceCode());
			ShopSource shopSource = shopSourceService.findByOrdenoSourceCode(
					ordenoSource.getOrdenoSourceCode()).get(0);// 根据店铺编码获取店铺信息
			// 获得库存信息
			GetSkuStoreUtil.getSkuStoreCode(backupTaskSkus, shopSource);

			if ("single".equals(batchTask.getType())) {
				batchTask.setType("单件");
			} else if ("multiple".equals(batchTask.getType())) {
				batchTask.setType("多件");
			}

			if (StatusEnums.FWAREHOUSE.getStatus().equals(
					batchTask.getBatchType())) {
				batchTask.setBatchType("分仓订单");
			} else {
				batchTask.setBatchType("总仓订单");
			}

			json.put("status", "1");
			json.put("content", backupTaskSkus);
			json.put("batchTask", batchTask);
			json.put("backupTask", backupTask);
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	@RequestMapping(value = "exportPickExcel/{backupTaskCode}")
	public void exportPickExcel(
			@PathVariable("backupTaskCode") String backupTaskCode,
			HttpServletResponse response) {
		BackupTask backupTask = null;
		BatchTask batchTask = null;
		try {
			List<BackupTaskSku> backupTaskSkus = backupTaskSkuService
					.findByBackupTaskCode(backupTaskCode);
			if (backupTaskSkus.isEmpty()) {
				return;
			}
			backupTask = backupTaskService.findByBackupTaskCode(backupTaskCode);
			batchTask = batchTaskService.findByBatchTaskCode(backupTask
					.getBatchTaskCode());
			OrdenoSource ordenoSource = ordenoSourceService
					.findByOrdenoSourceCode(batchTask.getShopSourceCode());
			ShopSource shopSource = shopSourceService.findByOrdenoSourceCode(
					ordenoSource.getOrdenoSourceCode()).get(0);// 根据店铺编码获取店铺信息
			// 获得库存信息
			GetSkuStoreUtil.getSkuStoreCode(backupTaskSkus, shopSource);

			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment; filename="
					+ backupTaskCode + ".xls");
			WritableWorkbook book = Workbook.createWorkbook(response
					.getOutputStream());
			WritableSheet sheet = book.createSheet("第一页", 0);

			WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.BOLD);
			WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
			int length = backupTaskSkus.size();

			sheet.addCell(new Label(0, 0, batchTask.getAreaGroupName()
					+ "  共计：" + Integer.toString(length) + " 种商品", wcf_center));

			sheet.setColumnView(0, 22);
			sheet.setColumnView(1, 15);
			sheet.setColumnView(2, 12);
			sheet.setColumnView(3, 18);
			sheet.setColumnView(4, 12);
			sheet.addCell(new Label(0, 1, "拣货批次号"));
			sheet.addCell(new Label(1, 1, "SKU"));
			sheet.addCell(new Label(2, 1, "数量"));
			sheet.addCell(new Label(3, 1, "名称"));
			sheet.addCell(new Label(4, 1, "库位"));
			sheet.addCell(new Label(5, 1, "属性"));

			for (int i = 0; i < length; i++) {
				BackupTaskSku backupTaskSku = backupTaskSkus.get(0);
				sheet.addCell(new Label(0, i + 2, backupTaskSku
						.getBackupTaskCode()));// 拣货批次号

				sheet.addCell(new Label(1, i + 2, backupTaskSku.getSkuId()));// sku
				sheet.addCell(new Label(2, i + 2, backupTaskSku.getRealQty()
						+ ""));// 数量
				sheet.addCell(new Label(3, i + 2, backupTaskSku.getSkuName()));
				sheet.addCell(new Label(4, i + 2, backupTaskSku.getStockLists()));
				sheet.addCell(new Label(5, i + 2, backupTaskSku.getSkuString()));

			}
			book.write();
			book.close();
		} catch (Exception e) {
			
		}
	}

	/**
	 * 查询作业批次
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "queryBackupTask")
	public String queryWorkBatch(
			@RequestParam(value = "sortType", defaultValue = "auto") String sortType,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			Model model, ServletRequest request, ServletResponse response)
			throws Exception {

		Map<String, Object> searchParams = Servlets.getParametersStartingWith(
				request, "_");

		String fromDateStr = (String) searchParams.get("fromDate");
		String toDateStr = (String) searchParams.get("toDate");
		String batchType = (String) searchParams.get("batchType");
		String workType = (String) searchParams.get("workType");
		String warehouseCode = (String) searchParams.get("warehouseCode");
		String customerCode = (String) searchParams.get("customerCode");
		String areaGroupCode = (String) searchParams.get("areaGroupCode");
		// 查找商户组
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject()
				.getPrincipal();
		List<Customers> customerList = this.customersService
				.loadCustomerByAuthority(curUser);
		model.addAttribute("customers", customerList);

		if (customerCode == null) { // 派友用户
			customerCode = customerList.get(0).getCustomerCode();
		}
		Customers customer = this.customersService
				.findByCustomerCode(customerCode);
		model.addAttribute("customer", customer);

		// 集发目的地网点
		List<AreaGroup> areaGroups = this.areaGroupService
				.loadAreaGroupByAuthority(customerCode);// loadByWarehouseType("paiu");
		model.addAttribute("areaGroups", areaGroups);

		model.addAttribute("areaGroupCode", areaGroupCode);
		model.addAttribute("status", 0);
		Date fromDate = null;
		Date toDate = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		if (StringUtils.isNotEmpty(fromDateStr)) {
			fromDate = sdf.parse(fromDateStr);
		}
		if (StringUtils.isNotEmpty(toDateStr)) {
			toDate = sdf.parse(toDateStr);
		}

		// 封装查询参数
		searchParams.put("customers", customerCode);
		searchParams.put("fromDate", fromDate);
		searchParams.put("toDate", toDate);
		searchParams.put("batchType", batchType);
		searchParams.put("workType", workType);
		searchParams.put("warehouseCode", warehouseCode);
		searchParams.put("areagroups", areaGroupCode);

		Page<BackupTask> workBatchList = this.backupTaskService
				.findBackupTaskStatus(pageNumber, PAGENUMBER, sortType,
						searchParams);
		model.addAttribute("backupTasks", workBatchList);

		List<AreaGroup> wmList = this.areaGroupService
				.loadAreaGroupByAuthority(curUser, customerCode);
		model.addAttribute("wmList", wmList);
		return "work/gather/backupTaskLists";
	}

	/**
	 * 已经装箱的商品发生变化
	 * 
	 * @param boxCode
	 * @param skuId
	 * @param index
	 * @param backupTaskCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxChangeBoxCodeSkus")
	public void ajaxInitReduceSkus(
			@RequestParam(value = "boxCode") String boxCode,
			@RequestParam(value = "skuId") String skuId,
			@RequestParam(value = "index") int index,
			@RequestParam(value = "backupTaskCode") String backupTaskCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		ShippedBoxDTO shippedBox = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			if (index == 1) {// 箱子新增商品
				shippedBox = shippedBoxService.addShippedBoxSkuId(boxCode,
						skuId);
			} else if (index == 0) {// 箱子减少商品
				shippedBox = shippedBoxService.reduceShippedBoxSkuId(boxCode,
						skuId);
			}
			if (shippedBox == null) {
				json.put("status", "-1");
				json.put("content", "该箱子不存在");
				out.print(json.toString());
				return;
			} else if ("-1".equals(shippedBox.getStatus())) {
				json.put("status", "-1");
				json.put("content", shippedBox.getReserve());
				out.print(json.toString());
				return;
			} else if ("finish".equals(shippedBox.getStatus())) {
				json.put("index", "1");

			} else if ("pending".equals(shippedBox.getStatus())) {
				json.put("index", "-1");

			}
			json.put("status", "1");
			json.put("content", shippedBox);
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 根据箱子编码获得箱子商品信息
	 * 
	 * @param boxCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxInitReduceSkus")
	public void ajaxInitReduceSkus(
			@RequestParam(value = "boxCode") String boxCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;

		try {
			json = new JSONObject();
			out = response.getWriter();
			List<ShippedBoxSkus> shippedBoxSkus = shippedBoxSkusService
					.findByBoxCode(boxCode);
			if (shippedBoxSkus.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "箱子编码有误");
				out.print(json.toString());
				return;
			}

			json.put("status", "1");
			json.put("content", shippedBoxSkus);
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 对任务进行分组
	 * 
	 * @param batchTaskCode
	 * @param number
	 * @param response
	 */
	@RequestMapping(value = "ajaxGroupBackupTask")
	public void ajaxGroupBackupTask(
			@RequestParam(value = "batchTaskCode") String batchTaskCode,
			@RequestParam(value = "number", defaultValue = "100") int number,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		BatchTask batchTask = null;
		List<GroupBackupTaskDTO> groupBackupTaskDTOs = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			batchTask = batchTaskService.findByBatchTaskCode(batchTaskCode);
			if (batchTask == null) {
				json.put("status", "-1");
				json.put("content", "该拣货批次不存在");
				out.print(json.toString());
				return;
			}
			groupBackupTaskDTOs = backupTaskService.getGroupBackupTasks(
					batchTaskCode, number, batchTask.getCustomerCode());
			if (groupBackupTaskDTOs.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "该拣货批次订单数为0");
				out.print(json.toString());
				return;
			}
			json.put("status", "1");
			json.put("content", groupBackupTaskDTOs);
			out.print(json.toString());
		} catch (Exception e) {
			batchTask.setStatus("pending");
			batchTaskService.save(batchTask);
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 导出exl表格
	 * 
	 * @param batchcode
	 * @param response
	 */
	@RequestMapping(value = "exportExcel/{backupTaskCode}")
	public void exportExcel(
			@PathVariable("backupTaskCode") String backupTaskCode,
			HttpServletResponse response) {
		List<BackupTaskOrdeno> backupTaskOrdenos = null;
		BackupTask backupTask = null;
		BatchTask batchTask = null;
		try {
			backupTask = backupTaskService.findByBackupTaskCode(backupTaskCode);
			batchTask = batchTaskService.findByBatchTaskCode(backupTask
					.getBatchTaskCode());
			backupTaskOrdenos = backupTaskOrdenoService
					.findByBackupTaskCode(backupTaskCode);

			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment; filename="
					+ backupTaskCode + ".xls");
			WritableWorkbook book = Workbook.createWorkbook(response
					.getOutputStream());
			WritableSheet sheet = book.createSheet("第一页", 0);

			WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.BOLD);
			WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
			int length = backupTaskOrdenos.size();

			sheet.addCell(new Label(0, 0, batchTask.getAreaGroupName()
					+ "  共计：" + Integer.toString(length) + " 单", wcf_center));

			sheet.setColumnView(0, 22);
			sheet.setColumnView(1, 15);
			sheet.setColumnView(2, 12);
			sheet.setColumnView(3, 18);
			sheet.setColumnView(4, 12);
			sheet.addCell(new Label(0, 1, "拣货批次号"));
			sheet.addCell(new Label(1, 1, "订单号"));
			sheet.addCell(new Label(2, 1, "来源单号"));
			sheet.addCell(new Label(3, 1, "时间"));
			sheet.addCell(new Label(4, 1, "能容运单号"));
			sheet.addCell(new Label(5, 1, "收件人名称"));
			sheet.addCell(new Label(6, 1, "收件人地址"));
			sheet.addCell(new Label(7, 1, "收件人手机"));

			DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			for (int i = 0; i < length; i++) {
				EdiOrder ediOrder = ediOrderService
						.findByOrdeno(backupTaskOrdenos.get(i).getOrdeno());
				sheet.addCell(new Label(0, i + 2, ediOrder.getBackupTaskCode()));// 拣货批次号

				sheet.addCell(new Label(1, i + 2, ediOrder.getOrdeno()));// 订单号
				sheet.addCell(new Label(2, i + 2, ediOrder.getFromno()));// 来源单号
				String creatTime = format.format(ediOrder.getCrtime());// 时间
				sheet.addCell(new Label(3, i + 2, creatTime));
				sheet.addCell(new Label(4, i + 2, ediOrder.getWaybillNo()));// 能容运单号
				sheet.addCell(new Label(5, i + 2, ediOrder.getRecena()));// 收件人名称
				sheet.addCell(new Label(6, i + 2, ediOrder.getAddres()));// 收件人地址
				sheet.addCell(new Label(7, i + 2, ediOrder.getMobile()));// 收件人手机

			}
			book.write();
			book.close();
		} catch (Exception e) {
			
		}
	}

	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private ShiroUser getShiroUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}

	/**
	 * 生成拣货任务
	 * 
	 * @param batchTaskCode
	 *            分拣批次号
	 * @param ordenos
	 *            订单号(:号分割)
	 * @param response
	 */
	@RequestMapping(value = "ajaxCreateBackupTask")
	public void ajaxCreateBackupTask(
			@RequestParam(value = "batchCode") String batchTaskCode,
			@RequestParam(value = "workOrderJsonText") String workOrderJsonText,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		ShiroUser user = getShiroUser();
		try {
			json = new JSONObject();
			out = response.getWriter();
			log.info("生成拣货任务开始--分拣批次号:" + batchTaskCode + "====ordenos="
					+ workOrderJsonText);
			JSONArray infoArray = JSONArray.fromObject(workOrderJsonText);
			Map<String, String> stockMap = new HashMap<String, String>();
			Map<String, Integer> ranknoMap = new HashMap<String, Integer>();
			for (Object info : infoArray) {
				Map<String, Object> map = (Map<String, Object>) info;
				String ordeno = (String) map.get("ordeno");
				String stockInfo = (String) map.get("stockInfo");
				Integer rankno = Integer
						.valueOf(map.get("rankno") == null ? "0" : map
								.get("rankno") + "");
				stockMap.put(ordeno, stockInfo);
				ranknoMap.put(ordeno, rankno);
			}

			BackupTask backupTask = backupTaskService.createBachupTask(
					stockMap, ranknoMap, batchTaskCode);

			if (backupTask == null) {
				json.put("status", "-1");
				json.put("content", "生成拣货任务批次错误");
				out.print(json.toString());
				return;
			}
			json.put("status", "1");
			json.put("content", 1);
			out.print(json.toString());

		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 生成拣货任务_1
	 * 
	 * @param batchTaskCode
	 *            分拣批次号
	 * @param ordenos
	 *            订单号(:号分割)
	 * @param response
	 */
	@RequestMapping(value = "ajaxCreateBackupTask_1")
	public void ajaxCreateBackupTask_1(
			@RequestParam(value = "batchCode") String batchTaskCode,
			@RequestParam(value = "workOrderJsonText") String workOrderJsonText,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		ShiroUser user = getShiroUser();
		try {
			json = new JSONObject();
			out = response.getWriter();
			log.info("生成拣货任务开始--分拣批次号:" + batchTaskCode + "====ordenos="
					+ workOrderJsonText);
			JSONArray infoArray = JSONArray.fromObject(workOrderJsonText);
			Map<String, String> stockMap = new HashMap<String, String>();
			Map<String, Integer> ranknoMap = new HashMap<String, Integer>();
			for (Object info : infoArray) {
				Map<String, Object> map = (Map<String, Object>) info;
				String ordeno = (String) map.get("ordeno");
				String stockInfo = (String) map.get("stockInfo");
				Integer rankno = Integer
						.valueOf(map.get("rankno") == null ? "0" : map
								.get("rankno") + "");
				stockMap.put(ordeno, stockInfo);
				ranknoMap.put(ordeno, rankno);
			}

			BackupTask backupTask = backupTaskService.createBachupTask_1(
					stockMap, ranknoMap, batchTaskCode);

			if (backupTask == null) {
				json.put("status", "-1");
				json.put("content", "生成拣货任务批次错误");
				out.print(json.toString());
				return;
			}
			json.put("status", "1");
			json.put("content", 1);
			out.print(json.toString());

		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

}
